package com.hiray.droidplugin.ui.main

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.hiray.droidplugin.R
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadListener
import com.liulishuo.filedownloader.FileDownloader
import com.morgoo.droidplugin.pm.PluginManager
import kotlinx.android.synthetic.main.fragment_main.*
import java.io.File

/**
 * A placeholder fragment containing a simple view.
 */
class PlaceholderFragment : Fragment() {

    val TAG = "PlaceholderFragment"
    private lateinit var pageViewModel: PageViewModel


    val apkUrl = "http://file.ji7.com/appfile/app-official-release-V1.4.3.apk"

//    val apkItems =
//        arrayListOf(Pair("http://file.ji7.com/appfile/app-official-release-V1.4.3.apk", "趣味星球"))

    companion object {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private const val ARG_SECTION_NUMBER = "section_number"

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        @JvmStatic
        fun newInstance(sectionNumber: Int): PlaceholderFragment {
            return PlaceholderFragment().apply {
                arguments = Bundle().apply {
                    putInt(ARG_SECTION_NUMBER, sectionNumber)
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        pageViewModel = ViewModelProviders.of(this).get(PageViewModel::class.java).apply {
            setIndex(arguments?.getInt(ARG_SECTION_NUMBER) ?: 1)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val root = inflater.inflate(R.layout.fragment_main, container, false)
        return root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        delPkg.setOnClickListener {
            val b = File(context?.filesDir, "planet.apk").delete()
            if (b)
                Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show()
        }
        Log.i(TAG, "onViewCreated: ${File(context?.filesDir, "planet.apk").length() / 1024 / 1024}MB")
        download.setOnClickListener {
            FileDownloader.getImpl()
                .create(apkUrl)
                .setPath(File(context?.filesDir, "planet.apk").absolutePath, false)
                .setListener(object : FileDownloadListener() {
                    override fun warn(task: BaseDownloadTask?) {
                        Log.i(TAG, "warn: ")
                    }

                    override fun completed(task: BaseDownloadTask?) {

                    }

                    override fun pending(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {

                    }

                    override fun error(task: BaseDownloadTask?, e: Throwable?) {

                        Log.i(TAG, "error: ${e?.message}")
                    }

                    override fun progress(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {
                        activity?.runOnUiThread {
                            status_text.text = "${(soFarBytes * 100) / totalBytes}"
                        }
                    }

                    override fun paused(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {

                    }

                })
                .addFinishListener {

                    activity?.runOnUiThread {
                        status_text.text = "下载完成"
                    }
                }
                .start()

            launchApp.setOnClickListener {
                val path = File(context?.filesDir, "planet.apk").absolutePath
                PluginManager.getInstance().installPackage(path, 0)
                val pgkManager = activity?.packageManager
                val archiveInfo = pgkManager?.getPackageArchiveInfo(path, 0)

                val intent = pgkManager?.getLaunchIntentForPackage(archiveInfo?.packageName)
                intent?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                startActivity(intent)
            }
        }
    }


}